package router

import (
	"broker/interface/iserver"
	"broker/struct/datapack"
	"broker/struct/model"
	"broker/utils/logger"
)

/**
 * @Description
 * @Author huan.wang
 * @Date 2021/4/30 10:58 上午
 **/

type UnSubscribeRouter struct {
	BaseRouter
}

func NewUnSubscribeRouter() *UnSubscribeRouter {
	return &UnSubscribeRouter{}
}

func (us UnSubscribeRouter) PreHandle(request iserver.IRequest) interface{} {
	usdp := datapack.NewUnSubscribeDatapack()
	unSubMsg, err := usdp.UnPack(request.GetData())
	if err != nil {
		logger.Error.Println("[UnSubscribe] unsubscribe message datapack err", err)
		return nil
	}
	return unSubMsg
}

func (us UnSubscribeRouter) Handle(request iserver.IRequest, param interface{}) interface{} {
	unSubMsg := param.(*model.UnSubscribeMessage)
	unSubscriber := model.NewSubscriber(request.GetConnection().GetConnID(), unSubMsg.TopicFilters)
	err := request.GetConnection().GetTcpServer().GetTopicManager().UnSubscribe(unSubscriber)
	if err != nil {
		logger.Error.Println("[UnSubscribe] delete subscriber err ", err)
		return nil
	}
	return unSubMsg
}

func (us UnSubscribeRouter) PostHandle(request iserver.IRequest, param interface{}) {
	unSubMsg := param.(*model.UnSubscribeMessage)
	//发送suback消息
	usadp := datapack.NewUnSubscribeAckDataPack()
	unSubAckMsg := model.NewUnSubscribeAckMessage()
	unSubAckMsg.PacketID = unSubMsg.PacketID
	msgData, err := usadp.Pack(unSubAckMsg)
	if err != nil {
		logger.Error.Println("[UnSubscribeACK] sub ack datapack err ", err)
	}
	unSubAckMsg.SetData(msgData)
	go request.GetConnection().SendMsg(unSubAckMsg)
}
